#!/usr/bin/env bash

set -euo pipefail

cd "$(dirname "${0}")/.."

checkout_repo() {
  local -r path="${1}"
  local -r repo="${2}"
  local -r sha="${3}"

  echo "Checking out github.com/${repo}#${sha} in ${path}"

  mkdir -p "${path}"
  pushd "${path}" >/dev/null

  if [[ ! -d ".git" ]]; then
    git init --quiet
    git remote add origin "https://github.com/${repo}.git"
    git fetch --quiet --depth 1 origin "${sha}"
  elif [[ "${sha}" != "$(git rev-parse HEAD)" ]]; then
    git fetch --quiet --depth 1 origin "${sha}"
  fi

  git checkout --quiet FETCH_HEAD

  popd >/dev/null

  echo
}

checkout_repo "./examples/luvit" "luvit/luvit" "9841bc17aaab32fa63e11063cf68f82da615eefd"

parse_examples() {
  local -r known_failures="$(cat script/known_failures.txt)"

  tree-sitter parse --quiet \
    "./examples/luvit/**/*.lua" \
    $(for file in ${known_failures}; do echo "!${file}"; done)

  declare -r example_count=$(find ./examples -name "*.lua" | wc -l)
  declare -r failure_count=$(wc -w <<< "${known_failures}")
  declare -r success_count=$(( ${example_count} - ${failure_count} ))
  declare -r success_percent=$(bc -l <<< "100*${success_count}/${example_count}")

  printf \
    "[Lua] Successfully parsed %d of %d example files (%.1f%%)\n" \
    ${success_count} ${example_count} ${success_percent}
}

parse_examples
